<?php

class backgroundColorComponents extends myComponents
{
  public function executeRender()
  {
    $this->structure  = $this->getRoute()->getObject();
    $this->background = false;
    
    
    /**
     * Draw the background
     */
    $img_file = sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . 'bg.png';
    
    if($this->structure->getBackground()) {
      if(is_file(sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . trim($this->structure->getBackground(), '#') . '.png')) {
        $this->background = '/web/uploads/' . trim($this->structure->getBackground(), '#') . '.png';
      } else {
        $source  = imagecreatefrompng($img_file);
        $target  = array(
            'r' => hexdec(substr($this->structure->getBackground(), 1, 2)), 
            'g' => hexdec(substr($this->structure->getBackground(), 3, 2)), 
            'b' => hexdec(substr($this->structure->getBackground(), 5, 2))
        );
        
        for($i = 0; $i < imagesx($source); $i++) {
          for($j = 0; $j < imagesy($source); $j++) {
            $color = imagecolorsforindex($source, imagecolorat($source, $i, $j));
            $color = max($color['red'], $color['green'], $color['blue']);
            $color = array(
              'r' => (($target['r'] * $color) / 255),
              'g' => (($target['g'] * $color) / 255),
              'b' => (($target['b'] * $color) / 255),
            );
            
            imagesetpixel($source, $i, $j, imagecolorallocate($source, $color['r'], $color['g'], $color['b']));
          }
        }
        
        imagejpeg($source, sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . trim($this->structure->getBackground(), '#') . '.png');
        $this->background = '/web/uploads/' . trim($this->structure->getBackground(), '#') . '.png';
      }
    } else $this->background = false;
  }
};